﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Events;
using Razre.Events;

namespace Razre.Base
{
    /// <summary>
    /// Class to provide base ViewModel functionality
    /// </summary>
    public class BaseViewModel : BaseNotificationObject
    {
        #region ctors

        /// <summary>
        /// Default constructor subscribes to the EventAggregator Theme Changed Event
        /// </summary>
        public BaseViewModel()
        {
            try
            {
                //Get the ThemeChangedEvent and subscribe to it
                ThemeChangedEvent themeChangedEvent = Settings.EventAggregator.GetEvent<ThemeChangedEvent>();
                themeChangedEvent.Subscribe(RefreshView);
            }
            catch (Exception ex)
            {
                throw new Exception("The EventAggregator in Settings was not set or the theme subscription failed", ex);
            }
        }

        #endregion

        #region properties

        public ContentControl View { get; set; }

        #endregion

        #region methods

        /// <summary>
        /// Method will cause the ViewModel to attempt to refresh its datatemplate
        /// </summary>
        /// <param name="refresh">Whether or not to refresh</param>
        public virtual void RefreshView(bool refresh)
        {
            if (refresh)
            {
                //Ensure the View is populated
                if (View != null)
                {
                    //try to find an associated DataTemplate
                    DataTemplate template = Application.Current.FindResource(new DataTemplateKey(this.GetType())) as DataTemplate;

                    //if template was found
                    if (template != null)
                    {
                        //reset the Views ContentTemplate to the newly found template
                        View.ContentTemplate = template;
                    }
                    else
                    {
                        throw new Exception(String.Format("Template Not Found, please ensure the DataTemplate is able to be found by Application Resources either manually or through the ThemeManager. Type Searching for is {0}", this.GetType().ToString()));
                    }
                }
                else
                {
                    throw new Exception(String.Format("View Not Found. Ensure the View was created properly. Type Searching for is {0}", this.GetType().ToString()));
                }
            }
        }

        #endregion
    }
}
